#region Using Directives

#endregion Using Directives

#region

using System;
using System.Configuration.Provider;
using System.Web;
using System.Web.Configuration;
using BuildMotion.MotionTracker.Common;
using BuildMotion.MotionTracker.Provider;

#endregion

namespace BuildMotion.MotionTracker
{
	/// <summary>
	/// This class provides access to the Notification service.
	/// </summary>
	public static class MotionTrackerService
	{
		#region Fields;

		private static readonly object _lock = new object();
		private static MotionTrackerProvider provider = null;
		private static MotionTrackerProviderCollection providerCollection = null;

		#endregion

		#region Methods

		/// <summary>
		/// The GetSection call requires the name of the section configured in the application configuration file. These
		/// names must match or the this method will not be able to retrieve the section information to load the type.
		/// </summary>
		private static void LoadProviders()
		{
			if(provider == null)
			{
				lock(_lock)
				{
					if(provider == null)
					{
						//Get reference to the section; The sectionName needs
						var section = (MotionTrackerServiceSection)WebConfigurationManager.GetSection("MotionTrackerService");
						if(section == null)
							throw new ProviderException("Missing config file/section for MotionTrackerService");
						providerCollection = new MotionTrackerProviderCollection();
						ProvidersHelper.InstantiateProviders(section.Providers, providerCollection, typeof(MotionTrackerProvider));
						provider = providerCollection[section.DefaultProvider];

						if(provider == null)
						{
							throw new ProviderException("Unable to load default provider for the MotionTrackerService.");
						}
					}
				}
			}
		}

		#endregion

		#region Static Service Methods

		/// <summary>
		/// Tracks the request.
		/// </summary>
		public static void TrackRequest(HttpApplication application)
		{
			LoadProviders();
			provider.TrackRequest(application);
		}

		public static void TrackRequest(HttpApplication application, Guid trackerId, Guid originId)
		{
			LoadProviders();
			provider.TrackRequest(application, trackerId, originId);
		}

		/// <summary>
		/// Use to retrieve the namne of the application using the provider.
		/// </summary>
		/// <returns></returns>
		public static string GetApplicationName()
		{
			LoadProviders();
			return provider.GetApplicationName();
		}

		#endregion

		#region Service API

		#endregion;

		///// <summary>
		///// Saves the tag.
		///// </summary>
		///// <param name="tagContext">The tag context.</param>
		///// <returns></returns>
		//public static TagContext SaveTag(TagContext tagContext)
		//{
		//    LoadProviders();
		//    return provider.SaveTag(tagContext);
		//}
	}
}